module amdar_csv_mod

  use datetime
  use string
  use amdar_mod
  use container
  use params_mod
  use data_translators_utils_mod

  implicit none

  private

  public amdar_csv_write

contains

  subroutine amdar_csv_write(file_path, flights, records)

    character(*), intent(inout) :: file_path
    type(hash_table_type), intent(inout) :: flights
    type(linked_list_type), intent(inout) :: records

    type(linked_list_iterator_type) it
    real ta, td, p
    integer i
    character(20) date_char

    if (file_path == '') file_path = 'amdar.csv'

    open(10, file=file_path, form='formatted')

    write(10, '(A, ",")', advance='no') 'sid'
    write(10, '(A, ",")', advance='no') 'time'
    write(10, '(A, ",")', advance='no') 'lon'
    write(10, '(A, ",")', advance='no') 'lat'
    write(10, '(A, ",")', advance='no') 'h'
    write(10, '(A, ",")', advance='no') 'p'
    write(10, '(A, ",")', advance='no') 'ta'
    !write(10, '(A, ",")', advance='no') 'td'
    write(10, '(A, ",")', advance='no') 'ws'
    write(10, '(A     )', advance='no') 'wd'
    write(10, *)

    it = linked_list_iterator(records)
    do while (.not. it%ended())
      select type (record => it%value)
      type is (amdar_record_type)
        write(10, '(A10  , ",")', advance='no') record%flight%name
        write(10, '(A15  , ",")', advance='no') record%time%isoformat()
        write(10, '(F12.6, ",")', advance='no') txt_value(record%lon)
        write(10, '(F12.6, ",")', advance='no') txt_value(record%lat)
        write(10, '(F12.2, ",")', advance='no') txt_value(record%h)
        write(10, '(F12.4, ",")', advance='no') txt_value(record%p)
        write(10, '(F12.4, ",")', advance='no') txt_value(record%ta)
        !write(10, '(F12.4, ",")', advance='no') txt_value(record%td)
        write(10, '(F12.4, ",")', advance='no') txt_value(record%ws)
        write(10, '(F12.4     )', advance='no') txt_value(record%wd)
        write(10, *)
      end select
      call it%next()
    end do

    close(10)

  end subroutine amdar_csv_write

end module amdar_csv_mod
